<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/***************************************************************************
 * 
 * Copyright (c) 2014 Baidu.com, Inc. All Rights Reserved
 * 
 **************************************************************************/
 
 
 
/**
 * @todo 广告控制器
 * @package conrtollers/admin 
 * @file ads.php
 * @author lihongliang01@baidu.com
 * @date 2014年11月29日 下午2:58:42
 * 
 *  
 **/

class Ads extends MY_ADMIN_Controller {
	public function __construct() {
		parent::__construct();
		$this->loadModel('Ads_model','Ads');
		
	}
	
	public function index() {
		$like = $this->_searchLike($this->Ads);
		$where = $this->_searchWhere($this->Ads);
		$map = array();
		if(!empty($like)) $map['like'] = $like;
		if(!empty($where)) $map['where'] = $where;
		$this->assign['result'] = $this->getPager($this->Ads,$map);
		$this->display();
	}
	
	public function create() {
		if($this->input->post(null,true)){
			return $this->save();
		}else{
			$this->display();
		}
	}
	
	public function edit($id){
		if($this->input->post(null,true)){
			return $this->save('ads/edit');
		}else{
			$res = $this->Ads->findByPk($id);
			if(empty($res)){
				return $this->showMessage('error_param',site_url('admin/ads'));
			}
			$this->assign['adv'] 	= $res[0];
			$this->display('ads/create.php');
		}
	}
	
	private function save($type=''){
		$redirect = getRedirect(base_url('admin/ads'));
	
		$this->load->library('form_validation');
		$this->lang->load('template');
	
		if ($this->form_validation->run($type) == FALSE){
			return $this->showMessage(validation_errors());
		}
		$data = $this->input->post(null,true);
		$mediaType = $data['media_type'];
		$files = array();
		$fileField = null;
		switch($mediaType){
			case 'image':
				$fileField = 'ad_image';
				break;
			case 'text':
				$data['ad_code'] = $data['ad_text'];
				break;
			case 'flash':
				unset($data['ad_link']);	//删除连接
				$fileField = 'ad_flash';
				break;
			case 'html':
			default:
				unset($data['ad_link']);	//删除连接
				break;
		}
		$data['start_at'] = time();
		$data['end_at'] = time();
		if(($id = $this->Ads->save($data))!==false){
			if(!empty($fileField)){
				if (!empty($_FILES[$fileField]['name'])) {
					$fileId = empty($data['id']) ? $id : $data['id'];
					$upload = $this->uploadLogoFiles($fileId, 'ads', $fileField);
					if (!$upload['result']) {
						$mes = $upload['error'];
						return $this->showMessage($mes,$redirect);
					}
					$ads = array('id'=>$fileId, 'ad_code'=>$upload['file']);
					if (($ret = $this->Ads->save($ads)) == false) {
						return $this->showMessage($this->Ads->_error);
					}
				}
			}
			$mes = 'mes_success';
			return $this->showMessage($mes,$redirect);
		}else{
			return $this->showMessage($this->Ads->_error);
		}
	}
}

/*End of file ads.php*/
/*Location ads.php */